#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>

int main(int argc,const char* argv[]){
    if(argc != 3){
        return -1;
    }
    int fd_r = open(argv[1],O_RDONLY);
    if(fd_r == -1){
        perror("open r err");
        return -1;
    }
    int fd_w = open(argv[2],O_WRONLY | O_TRUNC |O_CREAT,0666);//只写，并清空目标文件内容
    if(fd_w == -1){
        perror("open  w err");
        close(fd_r);
        return -1;
    }    


    off_t len= lseek(fd_r,0,SEEK_END);
    printf("文件长度%ld\n",len);
    
    int half_befor=len/2;//

    char*ch=(char*)malloc( half_befor+1 );
    if(ch == NULL){
        printf("ch malloc err\n");
        close(fd_r);
        close(fd_w);
        return -1;
    }
    lseek(fd_r,half_befor,SEEK_SET);//定位到中间，防止同时写入时被覆盖
    pid_t pid=-1;
    pid = fork();
    if(pid < 0){
        perror("fork err");
        free(ch);
        ch=NULL;
        close(fd_r);
        close(fd_w);
        return -1;
    }else if(pid == 0){
        int half_after=len-(len/2);//后一半长度
        read(fd_r,ch,half_after);//读后一半
        lseek(fd_w, half_befor,SEEK_SET);//fd_w定位到后一半
        write(fd_w,ch,half_after);//写后一半
    }else{
        
        lseek(fd_r,0,SEEK_SET);//fd_r定位到开头
        read(fd_r,ch, half_befor);//读前一半
        lseek(fd_w,0,SEEK_SET);//fd_w定位到开头
        write(fd_w,ch, half_befor);//写前一半
        wait(NULL);//回收子进程
        
    }

    //资源回收
    free(ch);
    ch=NULL;
    close(fd_r);
    close(fd_w);

    return 0;
}